<template>
    <div>
        <CardBox v-for="(item, index) in cardList" :key="item.id" :title="`巡查点${index + 1}`" style="padding-bottom: 32px">
            <BaseButton v-if="cardList.length > 1" slot="button" type="text" color="danger" icon="el-icon-delete" @click="handleDelete(index)">
                删除
            </BaseButton>
            <el-form ref="form" :model="item" :rules="rules" size="medium" label-width="86px">
                <el-row :gutter="24">
                    <el-col :xl="6" :lg="8">
                        <el-form-item label="方向" prop="direction">
                            <el-select v-model="item.direction" placeholder="请选择" clearable style="width: 100%" @change="handleDirectionChange(item, index)">
                                <el-option v-for="d in directionOptions" :key="d.value" :label="d.label" :value="d.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xl="6" :lg="8">
                        <el-form-item label="桥梁名称" prop="bridgeCode">
                            <el-select
                                v-model="item.bridgeCode"
                                :placeholder="item.direction && road ? '请选择' : '请先选择路线和方向'"
                                :disabled="!item.direction || !road"
                                style="width: 100%"
                                filterable
                                clearable
                                @change="handleBradageChange(item)"
                            >
                                <el-option v-for="m in item.bridgeList" :key="m.value" :label="m.label" :value="m.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xl="6" :lg="8">
                        <el-form-item label="中心桩号" prop="stake">
                            <el-input v-model.trim="item.stake" disabled placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xl="6" :lg="8">
                        <el-form-item label="桥梁编码" prop="code">
                            <el-input v-model.trim="item.code" disabled placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xl="6" :lg="8">
                        <el-form-item label="本期检查" prop="currentCheckDate">
                            <el-date-picker
                                v-model="item.currentCheckDate"
                                type="date"
                                placeholder="请选择"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xl="6" :lg="8">
                        <el-form-item label="上期检查" prop="lastCheckDate">
                            <el-date-picker
                                v-model="item.lastCheckDate"
                                type="date"
                                placeholder="请选择"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="上传图片">
                            <ImageUpload ref="imageUpload" :list="item.photos" :limit="100"></ImageUpload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <!-- 缺陷表格 -->
            <CulvertBridgeTable ref="culvertBridgeTable" type="bridge"></CulvertBridgeTable>
        </CardBox>

        <div class="add-btn" @click="handleAdd">添加巡查点</div>
    </div>
</template>

<script>
import { BTCBridgeModel } from '@/models'
import { DirectionOptions } from '@/config/constants'
import { uniqueId } from 'lodash-es'
import reconfirm from '@/utils/reconfirm'
import CulvertBridgeTable from '../components/CulvertBridgeTable.vue'

export default {
    name: 'CulvertCardList',
    components: {
        CulvertBridgeTable
    },
    props: {
        road: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            bridgeModel: new BTCBridgeModel(),
            directionOptions: DirectionOptions,
            culvertTypeOptions: [
                { fid: 1, name: '类型1' },
                { fid: 2, name: '类型2' }
            ],
            cardList: [{ fid: uniqueId(), bridgeList: [] }],
            form: {},
            rules: {
                direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
                bridgeCode: [{ required: true, message: '请选择桥梁', trigger: 'change' }],
                stake: [{ required: true, message: '请输入中心桩号', trigger: 'blur' }],
                code: [{ required: true, message: '请输入桥梁编码', trigger: 'blur' }],
                // lastCheckDate: [{ required: true, message: '请选择上期检查日期', trigger: 'change' }],
                currentCheckDate: [{ required: true, message: '请选择本期检查日期', trigger: 'change' }]
            },
        }
    },
    watch: {
        road(newValue) {
            if (newValue) {
                this.cardList.forEach((item, index) => {
                    this.clearForm(item, index)
                    this.getBridgeList(this.road, item.directionName, item)
                })
            }
        }
    },
    methods: {
        clearForm(item, index) {
            this.$set(item, 'bridgeList', [])
            this.$set(item, 'bridgeCode', '')
            this.$set(item, 'name', '')
            this.$set(item, 'stake', '')
            this.$set(item, 'code', '')
            this.$nextTick(() => {
                this.$refs['form'][index].clearValidate(['bridgeCode', 'stake'])
            })
        },
        handleDelete(index) {
            reconfirm({
                isPromise: false,
                callback: () => {
                    this.cardList.splice(index, 1)
                }
            })
        },
        handleValidate() {
            return new Promise((resolve, reject) => {
                const tableListValidateRes = this.tableListValidate()
                if (tableListValidateRes) {
                    this.$message.error('异常描述（性质、范围、程度）不能为空！')
                    resolve(false)
                    return
                }
                const list = []
                const validas = []
                this.$refs['form'].forEach((item, index) => {
                    list.push(
                        new Promise((resolve) => {
                            item.validate((valida) => {
                                validas.push(valida)
                                resolve()
                            })
                        })
                    )
                })
                Promise.all([...list])
                    .then(() => {
                        const res = !validas.some((item) => item === false)
                        resolve(res)
                    })
                    .catch((err) => {
                        reject(err)
                    })
            })
        },
        handleAdd() {
            this.cardList.push({ fid: uniqueId() })
            console.log(this.cardList)
        },
        getData() {
            this.$refs.imageUpload.forEach((item, index) => {
                this.cardList[index].photos = item.imgList.map((item) => item.response?.data?.objectUrl).toString()
            })
            this.$refs.culvertBridgeTable.forEach((item, index) => {
                this.cardList[index].content = item.tableList
            })
            this.cardList.forEach(item => {
                delete item.bridgeList
            })
            return this.cardList
        },
        tableListValidate() {
            const list = []
            this.$refs.culvertBridgeTable.forEach((item) => {
                item.tableList.forEach((item) => {
                    const hasValue = Object.values(item).some((m) => {
                        if (Array.isArray(m)) {
                            if (m.length > 0) {
                                return true
                            } else {
                                return false
                            }
                        } else if (Object.prototype.toString.call(m) === '[object Object]') {
                            if (Object.keys.length > 0) {
                                return true
                            } else {
                                return false
                            }
                        } else {
                            return !!m
                        }
                    })
                    if (hasValue) {
                        if (item.description) {
                            list.push(true)
                        } else {
                            list.push(false)
                        }
                    } else {
                        list.push(true)
                    }
                })
            })
            const res = list.some((item) => item === false)
            return res
        },
        handleDirectionChange(item, index) {
            this.clearForm(item, index)
            // 设置方向中文名
            const value = item.direction
            const currentDirection = this.directionOptions.find((item) => item.value === value) || {}
            item.directionName = currentDirection.label
            this.getBridgeList(this.road, item.directionName, item)
        },
        getBridgeList(road, direction, item) {
            if (road && direction) {
                const data = { highwayCode: road, direction, pageSize: 10000 }
                return this.bridgeModel.getList(data).then((res) => {
                    const list = res.list.map((item) => {
                        return {
                            ...item,
                            value: item.code,
                            label: item.name
                        }
                    })
                    this.$set(item, 'bridgeList', list)
                })
            }
        },
        handleBradageChange(item) {
            // 设置桥梁中文名和回填其他信息
            const value = item.bridgeCode
            const currentBridge = item.bridgeList.find((item) => item.value === value) || {}
            item.name = currentBridge.label

            // 回填桥梁中心桩号和编码
            item.stake = currentBridge.centerPointStake
            item.code = currentBridge.value
            console.log(value)
        }
    }
}
</script>

<style lang="scss" scoped>
.spe-item {
    ::v-deep {
        .el-form-item__label {
            text-align: center;
            padding: 0;
            &::before {
                display: none;
            }
        }
        .el-input,
        .el-input__inner {
            min-width: auto !important;
        }
    }
}

.add-btn {
    width: 100%;
    height: 64px;
    margin-top: 32px;
    background-color: #fff;
    border: 2px dotted rgb(217, 217, 217);
    border-radius: 5px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
